/*********************************************************************
	文件：	log.h
	环境：	Windows 10
	IDE：	Visual Studio 2019
	版本：	1.4.1910
	功能：	1、向 <文件名.txt> 文件末尾追加当前系统时间
			2、向 <FILE* stream> 指向的文件末尾追加当前系统时间
	备注：	1、目前只有默认日期格式，即YYYY/MM/DD HH:mm:SS
			2、支持换行和不换行两种形式
	更新：	Bug:文件流为空，写入异常 - 2019-10-13 09:54:45
			Bug:字符串定义常量要加const - 2019-10-13 10:01:02
	日期：	2019年10月12日23:48:36
	作者：	wowpH
*********************************************************************/
#pragma once
#pragma message("log.h - wowpH - 1.4.1910")

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define MAX_TIME_MODE_SIZE 20

const char* null_stream = "Stream is null, please open a file first.";

void get_local_time(char* buffer);

void log_time_filename(char* const filename);
void log_time_stream(FILE* const stream);

void log_time_line_filename(char* const filename);
void log_time_line_stream(FILE* const stream);

void open_file(FILE** stream, char* const filename);

inline void get_local_time(char* buffer) {
	time_t tt;
	time(&tt);
	struct tm stm;
	localtime_s(&stm, &tt);
	int offset = 0;
	sprintf_s(buffer + offset, 6, "%04d/", stm.tm_year + 1900);
	offset += 5;
	sprintf_s(buffer + offset, 4, "%02d/", stm.tm_mon + 1);
	offset += 3;
	sprintf_s(buffer + offset, 4, "%02d ", stm.tm_mday);
	offset += 3;
	sprintf_s(buffer + offset, 4, "%02d:", stm.tm_hour);
	offset += 3;
	sprintf_s(buffer + offset, 4, "%02d:", stm.tm_min);
	offset += 3;
	sprintf_s(buffer + offset, 3, "%02d", stm.tm_sec);
}

inline void log_time_filename(char* const filename) {
	FILE* stream = NULL;
	open_file(&stream, filename);
	log_time_stream(stream);
	fclose(stream);
}

inline void log_time_stream(FILE* const stream) {
	if (stream != NULL) {
		char time[MAX_TIME_MODE_SIZE];
		get_local_time(time);
		fprintf(stream, "%s", time);
	} else {
		printf("%s\n", null_stream);
		exit(-1);
	}
}

inline void log_time_line_filename(char* const filename) {
	FILE* stream = NULL;
	open_file(&stream, filename);
	log_time_line_stream(stream);
	fclose(stream);
}

inline void log_time_line_stream(FILE* const stream) {
	log_time_stream(stream);
	fprintf(stream, "\n");
}

inline void open_file(FILE** stream, char* const filename) {
	fopen_s(stream, filename, "a");
	if (*stream == NULL) {
		perror(filename);
		exit(-1);
	}
}
